//
//  HYPayManager.m
//  XPlayer
//
//  Created by liguoqing on 2023/12/1.
//

#import "HYPayManager.h"
// 测试环境
#define iapSandBoxUrl   @"https://sandbox.itunes.apple.com/verifyReceipt"
// 线上环境
#define iapReleaseUrl   @"https://buy.itunes.apple.com/verifyReceipt"

static HYPayManager * manager = nil;

@interface HYPayManager ()<SKRequestDelegate,SKPaymentTransactionObserver,SKProductsRequestDelegate>

@property(nonatomic,strong)PayRespBlock respBlock;

@property (nonatomic, strong) NSArray *productIDs;

@end

@implementation HYPayManager

+ (instancetype)shareManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[HYPayManager alloc]init];
    });
    return manager;
}

+ (void)releaseManager
{
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:manager];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

- (void)addObserverForPayment
{
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}

- (void)requestApplePayWithSelectIndex:(NSInteger)index respBlock:(PayRespBlock)respBlock
{
    [self addObserverForPayment];
    self.productId = self.productIDs[index];
    [HYHub loadMessage:NSLocalizedString(@"支付中...", nil)];
    self.respBlock = respBlock;
    if([SKPaymentQueue canMakePayments]){
        //请求商品
        NSArray *product = [[NSArray alloc] initWithObjects:self.productId,nil];
        NSSet *nsset = [NSSet setWithArray:product];
        SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
        request.delegate = self;
        [request start];
    }else{
        if(self.respBlock){
            self.respBlock(NO);
        }
        [HYHub showMessage:NSLocalizedString(@"不支持内购", nil)];
    }
}

#pragma mark SKProductsRequestDelegate
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    NSArray *product = response.products;
    if([product count] == 0){
        [HYHub showMessage:NSLocalizedString(@"暂无商品", nil)];
        return;
    }
    SKProduct *p = nil;
    // appleID ,商品id appleID就对应着苹果后台的商品ID
    NSString *appleID = self.productId;
    
    for (SKProduct *pro in product){
        //后台消费条目的ID与我这里需要请求的一样（用于确保订单的正确性）
        if([pro.productIdentifier isEqualToString:appleID]){
            p = pro;
        }
    }
    if (p !=nil) {
        SKPayment *payment = [SKPayment paymentWithProduct:p];
        //发送购买请求
        [[SKPaymentQueue defaultQueue] addPayment:payment];
    }
}

#pragma mark SKRequestDelegate
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error
{
    NSLog(@"请求商品失败");
    if(self.respBlock){
        self.respBlock(NO);
    }
    [HYHub dismiss];
}
- (void)requestDidFinish:(SKRequest *)request
{
    NSLog(@"请求商品完成");
}

#pragma mark SKPaymentTransactionObserver
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions
{
    for(SKPaymentTransaction *tran in transactions){
        switch (tran.transactionState)
        {
            case SKPaymentTransactionStatePurchased://交易完成
                NSLog(@"交易完成");
                //让服务器做二次认证,服务器发送到苹果服务器验证凭证
                // 订阅特殊处理
                if(tran.originalTransaction){
                    // 如果是自动续费的订单originalTransaction会有内容
                }else{
                    // 普通购买，以及 第一次购买 自动订阅
                }
                [self verifyPurchaseWithPaymentTransaction:tran];
               
                break;
            case SKPaymentTransactionStateFailed://交易失败
                 [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                //            [self failedTransaction:transaction];
                NSLog(@"交易失败");
                if(self.respBlock){
                    self.respBlock(NO);
                }
                [HYHub showMessage:NSLocalizedString(@"交易失败", nil)];
                break;
            case SKPaymentTransactionStateRestored://已经购买过该商品
                 [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                NSLog(@"已经购买过");
                if(self.respBlock){
                    self.respBlock(NO);
                }
                [HYHub dismiss];
                break;
            case SKPaymentTransactionStatePurchasing:      //商品添加进列表
                NSLog(@"商品添加进列表");
                
                break;
            default:
                break;
        }
    }
}

- (void)verifyPurchaseWithPaymentTransaction:(SKPaymentTransaction *)transaction
{
    //从沙盒中获取交易凭证并且拼接成请求体数据
    NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptUrl];
    NSString *receiptString = [receiptData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];//转化为base64字符串
    NSString *bodyString = [NSString stringWithFormat:@"{\"receipt-data\" : \"%@\"}", receiptString];//拼接请求数
    NSData *bodyData = [bodyString dataUsingEncoding:NSUTF8StringEncoding];
    //创建请求到苹果官方进行购买验证 测试环境
    NSURL*url = [NSURL URLWithString:iapReleaseUrl];
    NSMutableURLRequest *requestM = [NSMutableURLRequest requestWithURL:url];
    requestM.HTTPBody = bodyData;
    requestM.HTTPMethod = @"POST";
    //创建连接并发送同步请求
    NSURLSessionDataTask *task = [[NSURLSession sharedSession]dataTaskWithRequest:requestM completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if(error) {
            NSLog(@"验证购买过程中发生错误，错误信息：%@",error.localizedDescription);
            return;
        }
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"%@",dic);
        if([dic[@"status"]intValue]==0){
            NSLog(@"购买成功！");
            NSDictionary *dicReceipt = dic[@"receipt"];
            NSDictionary *dicInApp = [dicReceipt[@"in_app"]firstObject];
            NSString *productIdentifier = dicInApp[@"product_id"];//读取产品标识
            //如果是消耗品则记录购买数量，非消耗品则记录是否购买过
            dispatch_async(dispatch_get_main_queue(), ^{
                // 完成购买
                [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
                
                if([productIdentifier isEqualToString:self.productId]) {
                    if(self.respBlock){
                        self.respBlock(YES);
                    }
                }else{
                    if(self.respBlock){
                        self.respBlock(NO);
                    }
                }
                [HYHub showMessage:NSLocalizedString(@"感谢鼓励支持，您的赞助将用户app的深入开发", nil)];
            });
        }else{
            dispatch_async(dispatch_get_main_queue(), ^{
                [HYHub showMessage:NSLocalizedString(@"交易失败，未通过验证！", nil)];
            });
        }
    }];
    [task resume];
}

- (NSArray *)productIDs
{
    if(!_productIDs){
        _productIDs = @[@"a_bottle_water",@"a_bottle_drink",@"a_cup_coffee",@"a_chicken_leg",@"a_hamburger"];
    }
    return _productIDs;
}

@end
